/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.kedacom.demo.spring.event;

import java.util.logging.Logger;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;

/**
 *
 * @author xiaojinghai
 */
@Component
public class SpringApplicationListener implements ApplicationListener {

    private static final Logger logger = Logger.getLogger(SpringApplicationListener.class.getName());

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            logger.info("应用容器已刷新");
            ContextRefreshedEvent e = (ContextRefreshedEvent) event;
            if (e.getApplicationContext().getParent() == null) {//root application context 没有parent，他就是最大父容器,web应用中web容器是子容器.
                //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
            }
        }
        if (event instanceof ContextStartedEvent) {
            logger.info("应用容器已启动");
        }
        if (event instanceof ContextClosedEvent) {
            logger.info("应用容器已关闭");
        }
        if (event instanceof ContextStoppedEvent) {
            logger.info("应用容器已停止");
        }
        if (event instanceof MyEvent) {
            MyEvent e = (MyEvent) event;
            logger.info("收到自定义消息：" + e.getMessage());
        }
    }
}
